package com.qfedu.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.role.RoleMapper;
import com.qfedu.role.dto.StateDto;
import com.qfedu.role.dto.RoleDto;
import com.qfedu.role.pojo.Role;
import com.qfedu.role.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Transactional(readOnly = true)
    @Override
    public Page<Role> getRoles(RoleDto roleDto) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Role::getId,Role::getName, Role::getEnableStatus,
                Role::getEnName);

        String name = roleDto.getName();
        wrapper.like(StringUtils.hasLength(name), Role::getName, name);
        Integer enableStatus = roleDto.getEnableStatus();
        wrapper.eq(enableStatus != null, Role::getEnableStatus, enableStatus);

        Page<Role> page = new Page<>(roleDto.getCurrentPage(), roleDto.getPageSize());
        return page(page, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeRoleState(StateDto stateDto) {
        LambdaUpdateWrapper<Role> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Role::getEnableStatus, stateDto.getNewState());
        wrapper.eq(Role::getId, stateDto.getId());
        wrapper.eq(Role::getEnableStatus, stateDto.getOldState());
        return update(wrapper);
    }

    @Override
    public boolean save(Role role) {

        LambdaQueryWrapper<Role> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Role::getName,role.getName());
        Role role1=roleMapper.selectOne(wrapper);
        if(role1==null && roleMapper.insert(role)!=0){
            return true;
        }else{
            return false;
        }
    }

}
